package com.hqd.ch03.v50.boot.autoconfigure.web.servlet;

import com.hqd.ch03.v50.beans.factory.ObjectProvider;
import com.hqd.ch03.v50.boot.autoconfigure.condition.ConditionalOnClass;
import com.hqd.ch03.v50.boot.autoconfigure.condition.ConditionalOnMissingBean;
import com.hqd.ch03.v50.boot.autoconfigure.condition.SearchStrategy;
import com.hqd.ch03.v50.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
import com.hqd.ch03.v50.boot.web.embedded.tomcat.TomcatContextCustomizer;
import com.hqd.ch03.v50.boot.web.embedded.tomcat.TomcatProtocolHandlerCustomizer;
import com.hqd.ch03.v50.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import com.hqd.ch03.v50.boot.web.servlet.server.ServletWebServerFactory;
import com.hqd.ch03.v50.context.annotation.Bean;
import com.hqd.ch03.v50.context.annotation.Configuration;
import org.apache.catalina.startup.Tomcat;
import org.apache.coyote.UpgradeProtocol;

import javax.servlet.Servlet;
import java.util.stream.Collectors;

@Configuration(proxyBeanMethods = false)
public class ServletWebServerFactoryConfiguration {

    /**
     * 存在Servlet、Tomcat且不存在ServletWebServerFactory才进行创建
     */
    @Configuration(proxyBeanMethods = false)
    @ConditionalOnClass({Servlet.class, Tomcat.class, UpgradeProtocol.class})
    @ConditionalOnMissingBean(value = ServletWebServerFactory.class, search = SearchStrategy.CURRENT)
    static class EmbeddedTomcat {

        @Bean
        TomcatServletWebServerFactory tomcatServletWebServerFactory(
                ObjectProvider<TomcatConnectorCustomizer> connectorCustomizers,
                ObjectProvider<TomcatContextCustomizer> contextCustomizers,
                ObjectProvider<TomcatProtocolHandlerCustomizer<?>> protocolHandlerCustomizers) {

            TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
            //添加所有Connector配置
            factory.getTomcatConnectorCustomizers()
                    .addAll(connectorCustomizers.orderedStream().collect(Collectors.toList()));
            //添加所有Context配置
            factory.getTomcatContextCustomizers()
                    .addAll(contextCustomizers.orderedStream().collect(Collectors.toList()));
            //添加所有协议配置
            factory.getTomcatProtocolHandlerCustomizers()
                    .addAll(protocolHandlerCustomizers.orderedStream().collect(Collectors.toList()));
            return factory;
        }

    }
}